package com.sample.springbatch.job.demo.user;

import com.sample.springbatch.config.BaseConfig;
import com.sample.springbatch.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;

/**
 * @author zwg
 * @date 2019-05-11 10:59
 **/

@Configuration
public class UserConfig extends BaseConfig {

    Logger logger = LoggerFactory.getLogger(UserConfig.class);

    @Bean(name = "userJob")
    public Job importUserJob() {
        return jobBuilderFactory.get("userJob")
                .incrementer(new RunIdIncrementer())
                .flow(userStep())
                .end()
                .build();
    }

    @Bean
    public Step userStep() {
        return stepBuilderFactory.get("userStep")
                .<User, User> chunk(1)
                .reader(userJpaPagingItemReader(null))
                .processor(processor())
                .writer(userItemWriter())
                .build();
    }

    @Bean
    @StepScope
    public UserJpaPagingItemReader<User> userJpaPagingItemReader(@Value("#{jobParameters}") Map params){
        return new UserJpaPagingItemReader<User>(params);
    }

    @Bean
    public ItemWriter<User> userItemWriter() {
        return new ItemWriter<User>() {
            @Override
            public void write(List<? extends User> items) throws Exception {
                if(items!=null){
                    for (User user : items){
                        logger.info("user:{}",user);
                    }
                }
            }

        };
    }

    @Bean
    public ItemProcessor processor() {
        return new ItemProcessor<User,User>() {

            @Override
            public User process(User item) throws Exception {
                //item.setAge(item.getAge()+1);
                logger.info("user:{}",item);
                return item;
            }
        };
    }


}
